<template>
  <main class="spgl-wrap">
    <el-row :gutter="5">
      <el-form :inline="true" :model="formInline" label-width="80px" label-position="left" class="demo-form-inline">
        <el-col :span="8">
          <el-form-item :label="$t('goods.title')">
            <el-input v-model="formInline.title" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item :label="$t('goods.isSell')">
            <el-select v-model="formInline.isSell" placeholder="请选择商品状态">
              <el-option label="上架" :value="1" />
              <el-option label="下架" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('goods.type')" style="width: 80%">
            <el-select v-model="formInline.type" placeholder="请选择课程类型">
              <el-option label="课程商品" :value="1" />
              <el-option label="服务费" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('goods.grade')">
            <el-select v-model="formInline.grade" placeholder="请选择适用年级">
              <el-option label="初三" value="初三" />
              <el-option label="高三" value="高三" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('goods.lessonType')">
            <el-select v-model="formInline.lessonType" placeholder="请选择课程类型">
              <el-option label="1 v 1" :value="1" />
              <el-option label="1 v N" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchTableData">查询</el-button>
            <el-button type="primary">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <el-row>
      <el-col :span="24" :offset="22">
        <el-button type="primary" @click="onNewGoods" style="margin: 0 0 10px 15px">新建商品</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-table v-if="tableData.length > 0" :data="tableData" style="width: 100%">
          <el-table-column prop="code" label="商品编号" width="130" align="center">
            <template #default="scope">
              <div>
                <span style="margin-left: 10px">{{ scope.row.code }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="title" :label="$t('goods.title')" width="130" align="center" />
          <el-table-column prop="type" :label="$t('goods.type')" width="110" align="center">
            <template #default="scope">
              {{ useDict("product_type", scope.row.type) }}
            </template>
          </el-table-column>
          <el-table-column prop="lessonType" :label="$t('goods.lessonType')" width="110" align="center">
            <template #default="scope">
              <el-tag>{{ useDict("lessonType", scope.row.lessonType) }} </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="lessonForm" :label="$t('goods.lessonForm')" width="150" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.lessonForm <= 1" type="success">{{ useDict("lessonForm", scope.row.lessonForm) }} </el-tag>
              <el-tag v-else>{{ useDict("lessonForm", scope.row.lessonForm) }} </el-tag>
            </template>
          </el-table-column>
          <el-table-column :label="$t('goods.isSell')" prop="isSell" width="110" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.isSell" type="success">{{ useDict("product_issell", scope.row.isSell) }}</el-tag>
              <el-tag v-else type="danger">{{ useDict("product_issell", scope.row.isSell) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="grade" :label="$t('goods.grade')" width="130" align="center" />
          <el-table-column prop="payType" :label="$t('goods.payType')" width="110" align="center">
            <template #default="scope">
              {{ useDict("payType", scope.row.payType) }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" :label="$t('goods.createTime')" width="160" align="center" />
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button size="small" type="text" :style="{ color: !scope.row.isSell ? '#888888' : '' }" @click="handleEdit(scope.$index, scope.row)">{{ useDict("product_issell", scope.row.isSell ? 0 : 1) }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty :image-size="200" v-else/>
      </el-col>
      <el-col :span="24">
        <!-- 分页 -->
        <el-pagination
          v-model:currentPage="pageControls.currentPage"
          v-model:page-size="pageControls.pageSize"
          :page-sizes="[5, 10, 20, 30]"
          :small="pageControls.small"
          :disabled="pageControls.disabled"
          :background="pageControls.background"
          layout="total,sizes , prev, pager, next,jumper"
          :total="pageControls.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      /></el-col>
    </el-row>
    <AddNoGoods v-model:dialogVisible="dialogVisible" @confirmHandle="updateTable"></AddNoGoods>
    <section class="isSell-dialog">
      <el-dialog v-model="isSellDialog" :width="500" title="商品管理">
        <p>请注意，下架商品后，历史订单和排课仍然有效，新的订单和排课不再支持使用“下架商品”！</p>
        <p :style="{ color: 'red' }">当前有：XX订单购买了该商品，相关排课共计XX课时，涉及xx个学员</p>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="isSellDialog = false">{{ $t("cancel") }}</el-button>
            <el-button type="primary" @click="handleIsSell">{{ $t("confirm") }}</el-button>
          </span>
        </template>
      </el-dialog>
    </section>
  </main>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref, watch, getCurrentInstance } from "vue";
import baseService from "@/service/baseService";
import { useDict } from "@/hooks/useDict";
import AddNoGoods from "@/components/my/spgl/AddNoGoods.vue";
import { ElMessage } from "element-plus";
interface IForm {
  title: string;
  isSell: number | null;
  type: number | null;
  grade: number | null;
  lessonType: number | null;
}
interface IGoods {
  code: string;
  createId?: number;
  createTime: string;
  grade: string;
  id?: number;
  isSell: number;
  lessonForm: number;
  lessonType: number;
  payType: number;
  price?: number;
  status?: number;
  title: string;
  type: number;
}
interface IPage {
  currentPage: number;
  pageSize: number;
  small?: boolean;
  background?: boolean;
  disabled?: boolean;
  total?: number;
}
let dialogVisible = ref(false);
let isSellDialog = ref(false); // 上下架弹窗
let tableData: IGoods[] = reactive([]); // 表格数据
let isUpdateTable = ref<boolean>(false); // 是否更新表格
let rowData: IGoods = reactive({
  code: "",
  createId: 1,
  createTime: "2022-08-27 09:38:00",
  grade: "一年级",
  id: 1011,
  isSell: 0,
  lessonForm: 2,
  lessonType: 2,
  payType: 1,
  price: 2,
  status: 1,
  title: "sp001",
  type: 1
});
const formInline: IForm = reactive({
  // 表单数据
  title: "",
  isSell: null,
  type: null,
  grade: null,
  lessonType: null
});
// 表格分页
const pageControls = reactive<IPage>({
  currentPage: 1,
  pageSize: 5,
  small: false,
  background: true,
  disabled: false,
  total: 1
});
onMounted(() => {
  nextTick(() => {
    fetchGoodsList();
  });
});
// 监听表格是否需要进行更新
watch(
  () => isUpdateTable.value,
  () => {
    fetchGoodsList();
  }
);
// 添加完商品之后，需要重新表格
const updateTable = (isUpdate: boolean) => {
  isUpdateTable.value = isUpdate;
  isUpdate ? console.log("确认更新") : "";
};
const fetchGoodsList = async (
  param: { pageIndex: number; pageSize: number } = {
    pageIndex: pageControls.currentPage,
    pageSize: pageControls.pageSize
  }
) => {
  tableData.length = 0;
  // 商品列表获取
  const res = await baseService.post("/product/list", param);
  if (res.code === 200) {
    tableData.push(...res.data.records);
    pageControls.currentPage = Number(res?.data?.current);
    pageControls.pageSize = Number(res?.data?.size);
    pageControls.total = Number(res?.data?.total);
  } else {
    console.error("获取数据失败");
  }
  console.log(res, "商品管理");
};

const handleEdit = (index: number, row: IGoods) => {
  // 操作的回调
  console.log(index, row);
  isSellDialog.value = true;
  rowData = row;
};
const handleIsSell = () => {
  // 改变上下架的回调
  if (isSellDialog.value) {
    const data = baseService.post("/product/updateIsSell", Object.assign(rowData, { isSell: rowData?.isSell ? 0 : 1 }));
    data
      ?.then((res) => {
        ElMessage({
          message: rowData?.isSell ? "已上架" : "已下架",
          type: "success"
        });
      })
      .catch((err) => {
        ElMessage({
          message: "状态更改失败" + err,
          type: "success"
        });
      })
      .finally(() => {
        isSellDialog.value = false;
      });
  }
};
// const handleDelete = (index: number, row: IGoods) => {
//   console.log(index, row);
// };
const onNewGoods = () => {
  // 新建商品
  console.log("submit!");
  dialogVisible.value = true;
};
// 数据查询
const searchTableData = async (param = Object.assign(formInline, { pageIndex: pageControls.currentPage, pageSize: pageControls.pageSize })) => {
  tableData.length = 0;
  // 商品列表获取
  const res = await baseService.post("/product/list", param);
  if (res.code === 200) {
    tableData.push(...res.data.records);
    pageControls.currentPage = Number(res?.data?.current);
    pageControls.pageSize = Number(res?.data?.size);
    pageControls.total = Number(res?.data?.total);
  } else {
    console.error("获取数据失败");
  }
  console.log(res, "商品管理");
};
// 表格分页
const handleSizeChange = (val: number) => {
  // console.log(`${val} items per page`);
  pageControls.pageSize = val;
  fetchGoodsList();
};
const handleCurrentChange = (val: number) => {
  // console.log(`current page: ${val}`);
  pageControls.currentPage = val;
  fetchGoodsList();
};
</script>
<style lang="scss">
.spgl-wrap {
  .el-form-item {
    width: 80%;
    .el-select {
      width: 249px;
    }
  }
  .demo-pagination-block + .demo-pagination-block {
    margin-top: 10px;
  }
  .demo-pagination-block .demonstration {
    margin-bottom: 16px;
  }
}
</style>
